// 保存用户相关信息的模块
import { login, getUserInfo, getEmployeesById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      console.log(888)
      state.token = token
      // 数据持久化 -- 保存到cookie中
      setToken(token)
    },
    setUserInfo(state, data) {
      state.userInfo = data
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async login(store, data) {
      const res = await login(data)
      // 保存token
      store.commit('setToken', res)
      // 保存时间戳
      localStorage.setItem('loginTime', Date.now())
    },
    // 获取用户信息
    async getUserInfo(store) {
      const res = await getUserInfo()
      const result = await getEmployeesById(res.userId)
      console.log(32, result)
      store.commit('setUserInfo', { ...res, ...result })
    },
    logout(store) {
      // 删除token  --- 本地存储
      store.commit('removeToken')
      // 删除userInfo
      store.commit('removeUserInfo')
    }
  }
}
